export default {
  namespaced: true, // 命名空间
  state: {
    cartList: []
  },
  getters: {
    getTotal (state) {
      return state.cartList.reduce((total, item) => total + item.num, 0)
    },
    getTotalPrice (state) {
      return state.cartList
        .filter(item => item.checked)
        .reduce((total, item) => total + item.price * item.num, 0)
    },
    isAllChecked (state) {
      return state.cartList.every(item => item.checked)
    }
  },
  mutations: {
    addToCart (state, goods) {
      const oldGoods = state.cartList.find(item => item.proid === goods.proid)
      if (oldGoods) {
        oldGoods.num += goods.num
      } else {
        state.cartList.push(goods)
      }
    },
    /**
     * goods { proid: xxx, checked: false}
     */
    updateGoodsState (state, goods) {
      const oldGoods = state.cartList.find(item => item.proid === goods.proid)
      if (oldGoods) {
        oldGoods.checked = goods.checked
      }
    },
    /**
     * goods { proid: xxx, num: 2}
     */
    updateGoodsNum (state, goods) {
      const oldGoods = state.cartList.find(item => item.proid === goods.proid)
      if (oldGoods) {
        oldGoods.num = goods.num
      }
    },
    // 删除商品 proid
    deleteGoodsById (state, proid) {
      // 数组删除元素的方式 splice filter
      const index = state.cartList.findIndex(item => item.proid === proid)
      if (index > -1) {
        state.cartList.splice(index, 1)
      }
    },
    /**
     * checked 要变成的值
     */
    allSelectOrNot (state, checked) {
      state.cartList.forEach(item => {
        item.checked = checked
      })
    }
  },
  actions: {
    asyncDelete (context, proid) {
      // setTimeout(() => {
      context.commit('deleteGoodsById', proid)
      // }, 1000)
    }
  }
}
